package com.shqcjd.sinopecdemomobile.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.NewsListBean;
import com.shqcjd.sinopecdemomobile.ui.activity.NewsDetailActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.NewsAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseFragment;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.SpacesItemDecoration;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * 新闻模块fragment
 * Created by sy on 2019/5/8.
 */

public class NewsFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener{
    private static final int PAGE_SIZE = 7;
    private int mNextRequestPage = 1;
    @BindView(R.id.iv_toolbar_back)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.rv_news_list)
    RecyclerView rvNewsList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    private Context mContext;
    private NewsAdapter newsAdapter;
    private View notDataView;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    public static NewsFragment newInstance() {
        return new NewsFragment();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_news_layout;
    }

    @Override
    public void initView(View rootView) {
        mContext = getContext();
        tvToolbarCenter.setText("新闻列表");
        ivToolbarBack.setVisibility(View.GONE);

        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvNewsList.getParent(), false);
        initRefreshLayout();
        swipeLayout.setRefreshing(true);
        initNews();
    }

    @Override
    public void initData() {
        refresh();
    }


    private void initNews() {
        newsAdapter = new NewsAdapter();
        rvNewsList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvNewsList.addItemDecoration(new SpacesItemDecoration(0, 1, ContextCompat.getColor(getContext(),R.color.line)));
        rvNewsList.setAdapter(newsAdapter);
        newsAdapter.setOnLoadMoreListener(this,rvNewsList);
        newsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                NewsListBean.ItemsBean item = (NewsListBean.ItemsBean) adapter.getItem(position);
                Intent intent = new Intent(getContext(), NewsDetailActivity.class);
                intent.putExtra("newsId", item.id);
                startActivity(intent);
            }
        });
    }

    private void initRefreshLayout() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    private void refresh() {
        mNextRequestPage = 1;
        newsAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        Map<String, Integer> map = new HashMap<>();
        map.put("pageIndex", mNextRequestPage);
        map.put("pageSize", PAGE_SIZE);
        ApiService.getNewsList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<NewsListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<NewsListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            setData(true, retData.data.items);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        newsAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        newsAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }
                });
    }

    private void loadMore(){
        Map<String, Integer> map = new HashMap<>();
        map.put("pageIndex", mNextRequestPage);
        map.put("pageSize", PAGE_SIZE);
        ApiService.getNewsList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<NewsListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<NewsListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.items);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        newsAdapter.loadMoreFail();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void setData(boolean isRefresh, List data) {

        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                newsAdapter.setNewData(data);
            } else {
                newsAdapter.setNewData(null);
                newsAdapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                newsAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            newsAdapter.loadMoreEnd(isRefresh);
        } else {
            newsAdapter.loadMoreComplete();
        }
    }


}
